// router.js
import { RouterMount, createRouter } from 'uni-simple-router'
import config from '@/common/config.js'

const routerError = function ({ type }) {
  // #ifdef APP-PLUS
  // 请勿删除此代码块
  if (type === 3) {
    router.$lockStatus = false
    uni.showModal({
      title: '提示',
      content: '您确定要退出应用吗？',
      success: function (res) {
        if (res.confirm) {
          let main = plus.android.runtimeMainActivity()
          plus.runtime.quit = function () {
            main.moveTaskToBack(false)
          }
          plus.runtime.quit()
        }
      }
    })
  }
  // 请勿删除此代码块
  // #endif
}

const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM,
  routerErrorEach: routerError,
  applet: {
    animationDuration: 300 //默认 300ms  v2.0.6+
  },
  routes: [...ROUTES]
})

//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
  let token = wx.getStorageSync('token')
  if (token) {
    if (to.path === '/pages/login/index') {
      next({ path: '/pages/index/index', NAVTYPE: 'replace' })
    }
  } else {
    /* 不存在token */
    if (config.whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      uni.removeStorageSync('token')
      next({ path: '/pages/login/index', NAVTYPE: 'replaceAll' })
    }
  }
})

// 全局路由后置守卫
router.afterEach((to, from) => {
  // console.log('跳转结束')
})

export { router, RouterMount }
